<!--
  功能说明：表单示例页面，包含基础校验与提交演示。
-->
<template>
  <div>
    <h2>表单提交与验证</h2>
    <form @submit.prevent="onSubmit">
      <div>
        <label>名称：</label>
        <input v-model="form.name" />
        <span class="error" v-if="errors.name">{{ errors.name }}</span>
      </div>
      <div>
        <label>年龄：</label>
        <input v-model.number="form.age" type="number" min="0" />
        <span class="error" v-if="errors.age">{{ errors.age }}</span>
      </div>
      <div>
        <label>邮箱：</label>
        <input v-model="form.email" type="email" />
        <span class="error" v-if="errors.email">{{ errors.email }}</span>
      </div>
      <button type="submit">提交</button>
    </form>
    <div v-if="result" class="ok">提交成功：{{ pretty(result) }}</div>
  </div>
</template>

<script>
import { post } from '../api/http'

export default {
  name: 'FormDemoPage',
  data() {
    return {
      form: { name: '', age: null, email: '' },
      errors: {},
      result: null
    }
  },
  methods: {
    validate() {
      const e = {}
      if (!this.form.name) e.name = '名称为必填项'
      if (this.form.age == null || this.form.age < 0) e.age = '年龄需为非负数'
      if (this.form.email && !/.+@.+\..+/.test(this.form.email)) e.email = '邮箱格式不正确'
      this.errors = e
      return Object.keys(e).length === 0
    },
    async onSubmit() {
      if (!this.validate()) return
      try {
        const res = await post('/form/submit', this.form)
        this.result = res
      } catch (err) {
        // 错误场景验证由拦截器统一处理
      }
    }
  }
}
</script>

<style>
.error { color: #c00; margin-left: 8px; }
.ok { margin-top: 12px; color: #2e7d32; }
</style>